var Category = function(categoryId,categoryName) {
	this.CategoryId= categoryId;
	this.CategoryName = categoryName;
}

var Book = function(id, pic, name, price){
	this.BookId = id;
	this.Pic = pic;
	this.Name= name;
	this.Price = price;
}

var ListBook = function(categories, books){
	this.Categories = categories;
	this.Books = books;
}

	var page = 0;
	var posDTO= 0;
	var pageTotal = 0;
	var limit= 48;
	var items= 12;

	var categoriesDTO;
	var booksDTO;

function setPageServiceAllBook(categoryId,keyword){
        this.page =0;
	    callServiceAllBooks(categoryId,keyword);
	    callServiceCategory();
	    createCategoriesNode(categoriesDTO,booksDTO);
}

function setPageServicePaging(categoryId,keyword){
	    callServiceAllBooks(categoryId,keyword);
	    createCategoriesNode(categoriesDTO,booksDTO);
}
function callServiceAllBooks(categoryID,keyWord){
		 	function callService(){
                 ajax.get({
                             url : "http://localhost:8080/book-service/public/book/store/allbook?",
                             param : {
                                 "start" : page * items,
                                 "limit" : limit,
                                 "categoryId" : categoryID != null ? categoryID : 0,
                                 "keyWord": keyWord
                             },
                             success : function(data, xhr) {
                                 var status = parseInt(data.childNodes[0].getAttributeNode("status").nodeValue);
                                 if(status == -1){
                                     alert("Không có sách!!");
                                 }else {
                                     var count = parseInt(data.childNodes[0].getAttributeNode("countTotal").nodeValue);
                                     if(count%items == 0){
                                         pageTotal = parseInt(count/items);
                                     }else{
                                         pageTotal = parseInt(count/items) + 1;
                                     }
                                 }
                                 posDTO = 0;
                                 var books = createBooksForCategoryPage(data);
                                 booksDTO = books;
                             },
                             failure : function(xhr) {
                                 console.log("fail");
                             }
                         });
             }

		if(this.page % 4 == 0) {
			showLoading();
			callService();
		} else {
            createCategoriesNode(categoriesDTO,booksDTO);
		}
}

function callServiceCategory(){
			ajax.get({
			 url : "http://localhost:8080/book-service/public/book/store/category",
			 
			 success : function(data, xhr) {
			 	//isFinishCategory = true;
			 	var categories = createCategories(data);
			 	categoriesDTO = categories;
				//self.updateData();
			 },
			 failure : function(xhr) {
				 console.log("fail");
			 }
		 });
}

function createCategories(categories){
		var arrCategories = [];
		var result = [];
		var category = null;

		arrCategories = categories.getElementsByTagName("category");
		for(var i=0;i<arrCategories.length; i++) {
			category = new Category(arrCategories[i].getElementsByTagName("categoryId")[0].childNodes[0].nodeValue, arrCategories[i].getElementsByTagName("categoryName")[0].childNodes[0].nodeValue);
			result.push(category);	
		}
		return result;
}

function createBooksForCategoryPage(books){
		var arrBooks = [];
		var result = [];
		var book = null;


		arrBooks = books.getElementsByTagName("book");
		for(var i=0;i<arrBooks.length; i++) {
			book = new Book(arrBooks[i].getElementsByTagName("bookId")[0].childNodes[0].nodeValue, arrBooks[i].getElementsByTagName("picture")[0].childNodes[0].nodeValue, arrBooks[i].getElementsByTagName("bookName")[0].childNodes[0].nodeValue, arrBooks[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
			result.push(book);	
		}
		
		return result;
}

function createCategoriesNode(arrCategories,arrBooks){
	var key = "books";
		addActive(key);
		var rootNodeCategory = $id("category-list");
		var category = null;
		var nodeUl=null;
		var nodeLi=null;
		var nodeCategory = null;
		var lengthCategory = arrCategories.length;

		// Declare ListBook
		var rootNodeListBook = $id("productItems");
		var book = null;
		var nodeItem = null;
		var nodeImg = null;
		var nodeItembot = null;
		var nodeName = null;
		var nodePrice = null;
		var lengthListBook = arrBooks.length;
		var pos = posDTO * 12;

		// Delete child node
		rootNodeCategory.innerHTML = "";
		rootNodeListBook.innerHTML = "";

		// Set node Category
        var self = this;
		nodeUl = createNode("ul");
		for (var i = 0; i < lengthCategory; i++) {
			category = arrCategories[i];
			
			nodeLi = createNode("li");
			
			nodeCategory = createNode("a");
			nodeCategory.setText(category.CategoryName);
			nodeCategory.setAttribute("href","#");			
			nodeCategory.setAttribute("categoryId", category.CategoryId);
			nodeCategory.addEventListener("click", function(event) {	
				page = 0;							
				callServiceAllBooks(parseInt(event.currentTarget.attributes.categoryId.textContent),null);
				createCategoriesNode(categoriesDTO,booksDTO);
			});

			nodeUl.appendChild(nodeLi);
			nodeLi.appendChild(nodeCategory);
		}
		rootNodeCategory.appendChild(nodeUl);

		lengthListBook = pos + 12 > lengthListBook ? lengthListBook : pos + 12;
		// Set node ListBook
		for (var i = pos; i < lengthListBook; i++) {
			book = arrBooks[i];

			nodeItem = createNode("a");
			nodeItem.addClass("item");
			nodeItem.setAttribute("href","#");
			nodeItem.setAttribute("id",book.BookId);
			nodeItem.addEventListener("click", getProductDetail,false); 

			nodeImg = createNode("img");
			nodeImg.addClass("item-img");
			nodeImg.src = book.Pic;
			
			nodeItembot = createDiv();
			nodeItembot.addClass("item-bot");

			nodeName = createDiv();
			nodeName.addClass("item-name");
			nodeName.setText(book.Name);

			nodePrice = createDiv();
			nodePrice.addClass("item-price");
			nodePrice.setText(book.Price);
			
			rootNodeListBook.appendChild(nodeItem);

			nodeItem.appendChild(nodeImg);
			nodeItem.appendChild(nodeItembot);

			nodeItembot.appendChild(nodeName);
			nodeItembot.appendChild(nodePrice);
		}
}

//for pagging
function callNext() {
		if(page != pageTotal - 1) {
			page++;
			posDTO++;
			setPageServicePaging();
		}
	}
	
function callPrevious() {
		if(page != 0) {
			page--;
			posDTO--;
			setPageServicePaging();
		}
	}

function callFirst() {
		if(page != 0) {
			page = 0;
			posDTO = 0;
			setPageServicePaging();
		}
	}

function  callLast() {
		if(page != pageTotal - 1) {
			page = pageTotal - 1;
			posDTO = page;
			setPageServicePaging();
		}
	}
	
	
            

